package com.azxc.rapid.auth.granter;

 import com.azxc.rapid.auth.constant.AuthConstant;
import com.azxc.rapid.auth.jianguan.SuperviseAuthenticationToken;
import com.azxc.rapid.auth.service.RapidUserDetails;
import com.azxc.rapid.auth.sso.SsoAuthenticationToken;
import com.azxc.rapid.auth.utils.CheckSign;
import com.azxc.rapid.auth.utils.TokenUtil;
import com.azxc.rapid.core.redis.cache.RapidRedis;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.core.tool.support.Kv;
import com.azxc.rapid.core.tool.utils.Func;
import com.azxc.rapid.core.tool.utils.WebUtil;
import com.azxc.rapid.supervise.feign.ISuperviseClient;
import com.azxc.rapid.system.user.entity.User;
import com.azxc.rapid.system.user.entity.UserInfo;
import com.azxc.rapid.system.user.enums.UserEnum;
import com.azxc.rapid.system.user.feign.IUserClient;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 统一认证TokenGranter
 */
public class SSoTokenGranter extends AbstractTokenGranter{

	private static final String GRANT_TYPE = "sso";

	private final AuthenticationManager authenticationManager;

	private RapidRedis rapidRedis;


	private  IUserClient userClient;

	public static String SECRET_KEY="asdfsafasdfasdfasdfasdfa";

	public SSoTokenGranter(AuthenticationManager authenticationManager,
                           AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, RapidRedis rapidRedis, IUserClient userClient) {
		this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
		this.rapidRedis = rapidRedis;
		this.userClient=userClient;
	}

	protected SSoTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                              ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
		super(tokenServices, clientDetailsService, requestFactory, grantType);
		this.authenticationManager = authenticationManager;
	}

	@Override
	protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
		HttpServletRequest request = WebUtil.getRequest();


		Map<String, String> map = new LinkedHashMap<>(tokenRequest.getRequestParameters());
		Object obj = ((HashMap) map).clone();
		Map<String, String> map2 = (Map<String, String>) obj;
		map2.remove("reqTime");
		map2.remove("sign");
		//todo 进行加密解密
		/*boolean check=CheckSign.checkSign(map2,map.get("sign"),SECRET_KEY);
		if(!check){
			throw new InvalidGrantException("sso 验证错误！");
		}*/
		String uid = map.get("uid");
		String tenantId = Func.toStr(request.getHeader(TokenUtil.TENANT_HEADER_KEY), TokenUtil.DEFAULT_TENANT_ID);

		RapidUserDetails rapidUserDetails;
		R<User>userR= userClient.userInfoById(Long.valueOf(uid));
		if(!userR.isSuccess()||null==userR.getData()||userR.getData().getAccount()==null){
			throw new InvalidGrantException("无该用户");
		}
		R<UserInfo> result= userClient.userInfo(tenantId, userR.getData().getAccount(), UserEnum.WEB.getName());
		if (result.isSuccess()) {
			User user = result.getData().getUser();
			Kv detail = result.getData().getDetail();
			if (user == null) {
				throw new InvalidGrantException("sso grant failure, user is null");
			}
			rapidUserDetails = new RapidUserDetails(user.getId(),
				tenantId, result.getData().getOauthId(), user.getName(), user.getRealName(), user.getDeptId(), user.getPostId(), user.getRoleId(), Func.join(result.getData().getRoles()),null,
				user.getAccount(), AuthConstant.ENCRYPT + user.getPassword(), detail, true, true, true, true,
				AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		} else {
			throw new InvalidGrantException("sso grant failure, feign client return error");
		}


		Authentication userAuth = new SsoAuthenticationToken(rapidUserDetails,AuthorityUtils.commaSeparatedStringToAuthorityList(Func.join(result.getData().getRoles())));
		((AbstractAuthenticationToken) userAuth).setDetails(map);
		//userAuth = authenticationManager.authenticate(userAuth);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);

		// If the username/password are wrong the spec says we should send 400/invalid grant
		/*if (userAuth == null || !userAuth.isAuthenticated()) {
			throw new InvalidGrantException("Could not authenticate user: " + userR.getData().getAccount());
		}
		((AbstractAuthenticationToken) userAuth).setDetails(rapidUserDetails);
		OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);*/
		return new OAuth2Authentication(storedOAuth2Request, userAuth);
	}


}
